package com.example.app.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

public class HttpClient {
    public static HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    public static HttpSession session=request.getSession();
    private static final Logger LOG = LoggerFactory.getLogger(HttpClient.class);
    /**
     * post请求接口
     * @param uri
     * @param json
     * @return
     */
    public static String postClient(String uri, String json) {
        HttpURLConnection connection=null;
        BufferedReader reader=null;
        try {
            //创建连接
            URL url = new URL(uri);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();
            // POST请求
            OutputStream out = connection.getOutputStream();
            out.write(json.getBytes());
            out.flush();
            out.close();
            LOG.debug(json);
            // 读取响应
            reader= new BufferedReader(new
                    InputStreamReader(connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer();
            while ((lines = reader.readLine()) != null) {
//                lines = URLDecoder.decode(lines, "utf-8");
                sb.append(lines);
            }
            return sb.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                reader.close();
                // 断开连接
                connection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return "连接错误";
    }

    /**
     * 在指定url后追加参数
     * @param url
     * @param data 参数集合 key = value
     * @return
     */
    public static String appendUrl(String url, Map<String, String> data) {
        String newUrl = url;
        StringBuffer param = new StringBuffer();
        for (String key : data.keySet()) {
            //排除空值请求
            if(!ObjectUtils.isEmpty(data.get(key))) {
                param.append(key + "=" + data.get(key) + "&");
            }
        }
        String paramStr = param.toString();
        paramStr = paramStr.substring(0, paramStr.length() - 1);
        if (newUrl.indexOf("?") >= 0) {
            newUrl += "&" + paramStr;
        } else {
            newUrl += "?" + paramStr;
        }
        return newUrl;
    }

}
